import Vue from 'vue'
import Vuex from "vuex"
import {getProducts} from "./api/shop"

Vue.use(Vuex);

let store = new Vuex.Store({
  state:{
    products: getProducts(), //放置产品数据
    carts:[]//购物小车数据
  },
  mutations:{
    addToCarts:function (state,product) {
        // console.log(state,product);
        
        // state.carts.push(product);
        //商品判断
        //1.商品在不在购物车中
       let index = state.carts.findIndex((cart,index)=>{
          if(cart.id === product.id){
            return true;
          }
        })
        
         if(index !=-1){
            //存在数量++
           state.carts[index].num++;
         }else{
           //不存在设置初始量为1
           let cart = JSON.parse(JSON.stringify(product));
           cart.num = 1;
           state.carts.push(cart)
         }
    }
  }
})

export default store;